﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.With.Apliaction.Command.InventoryCommand;
using DAL;
using MediatR;
using System.Data;

namespace B.S.BaseData.Manage.Api.With.Apliaction.CommandHandler.StoreCommand
{
    /// <summary>
    /// 入库删除
    /// </summary>
    public class StoreDeleteCommandHandler : IRequestHandler<StoreDeleteCommand, ApiReqult<object>>
    {
        private readonly DBHelper _dbHelper;

        public StoreDeleteCommandHandler(DBHelper dbHelper)
        {
            _dbHelper = dbHelper;
        }

        /// <summary>
        /// 执行入库逻辑删除操作
        /// </summary>
        /// <param name="request">包含要删除记录ID的请求</param>
        /// <returns>包含操作结果的ApiReqult对象</returns>
        public async Task<ApiReqult<object>> Handle(StoreDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<object>();

            // 手动将参数值嵌入到 SQL 语句中
            string sql = $"UPDATE ManagementModels SET IsDelete = 1 WHERE Id = {request.Id} AND IsDelete = 0";

            try
            {
                int rowsAffected = _dbHelper.NonQuery(sql);
                result.Code = rowsAffected > 0 ? ApiEnum.删除成功 : ApiEnum.删除失败;
                result.Msg = rowsAffected > 0 ? "入库记录逻辑删除成功" : "未找到未删除的入库记录或记录已被删除";
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.删除失败;
                result.Msg = $"入库记录逻辑删除失败：{ex.Message}";
            }

            return result;
        }
    }
}